﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PJ.Business;
using Microsoft.Practices.Composite.Events;
using System.Collections.ObjectModel;
using System.Collections;
using PJ.Data;

namespace PJ.Presentation
{
    public abstract class EntityFragmentListViewModel<TEntityFragmentModel> : BusinessObjectListViewModel<TEntityFragmentModel>, IEntityFragmentListViewModel
        where TEntityFragmentModel : class, IEntityFragmentModel

    {
        #region Constructor

        protected EntityFragmentListViewModel(IView view, IEventAggregator aggregator,
            IEntityFragmentService service)
            : base(view, aggregator, service)
        {
        }

        protected EntityFragmentListViewModel()
        {
        }

        #endregion

            /// <summary>
        /// Handle the owner change
        /// </summary>
        /// <param name="args">the entity id of the owner</param>
        public virtual void ParentChange(EntityEventArg args)
        {
            string parentId;
            if (args == null)
                parentId = null;
            else
                parentId = args.Id;
            if (parentId != ParentId)
            {
                ParentId = parentId;
                if (parentId == null || parentId == "")
                    SetValues(null);
                else
                    SetValues(Service.GetFragments(ParentId, GetDataMode.CachedFind));
            }
        }


        #region Interface implementation

        public override void InitializingNewItem(IBusinessObjectModel newItem)
        {
            if (newItem == null)
                throw new ArgumentNullException("newItem");
            if (ParentId == null || ParentId == "")
                throw new Exception("can't create new item if parent id not defined");
            newItem.Service = Service;
            ((IEntityFragmentModel)newItem).OwnerId = ParentId;
        }


        #endregion

        #region Protected

        new protected IEntityFragmentService Service
        {
            get { return (IEntityFragmentService)base.Service; }
        }

        protected string ParentId
        {
            get { return _ParentId; }
            set { _ParentId = value; }
        }

        #endregion

        #region Fields

        private string _ParentId;

        #endregion



    }
}
